package com.voltmao.service.application.intent;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.voltmao.persistent.mapper.*;
import com.voltmao.persistent.model.*;
import com.voltmao.service.application.sys.MessageTemplateServiceImpl;
import com.voltmao.service.application.sys.RegionServiceImpl;
import com.voltmao.webpro.frame.dto.DataPage;
import com.voltmao.webpro.utils.ParamsUtil;
import com.voltmao.webpro.utils.PropertiesUtils;
import com.voltmao.webpro.utils.StringUtils;

import java.util.*;

/**
 * 意向渠道服务类
 * @author zya
 */
@Service
public class IntentUserServiceImpl {
    @Autowired
    SysDictionaryMapper sysDictionaryMapper;

    @Autowired
    ProviderUserMapper providerUserMapper;

    @Autowired
    ProviderUserSbgsAzywgsMapper providerUserSbgsAzywgsMapper;

    @Autowired
    ProviderUserSbgsMapper providerUserSbgsMapper;

    @Autowired
    ProviderUserGxlqdMapper providerUserGxlqdMapper;

    @Autowired
    ProviderUserSdgsMapper providerUserSdgsMapper;

    @Autowired
    IntentUserMapper intentUserMapper;

    @Autowired
    IntentUserAssignMapper intentUserAssignMapper;

    @Autowired
    RegionServiceImpl regionService;

    @Autowired
    MessageTemplateServiceImpl messageTemplateService;

    /**
     * 安装运维公司
     */
    private final String AZYWGS = "azywgs";
    /**
     * 设备公司
     */
    private final String SBGS = "sbgs";
    /**
     * 售电公司
     */
    private final String SDGS = "sdgs";
    /**
     * 关系类渠道
     */
    private final String GXLQD = "gxlqd";
    /*
    * 完善信息，如营业执照等
    * 1.判断渠道商类型，共四种，公共信息写入provider_user
    *   其他信息根据类型写入不同的表
    * */

    @Transactional(rollbackFor = Exception.class)
    public boolean completeInfo(Map<String,Object> params) throws RuntimeException{
        //检查参数完整性
        String[] checkParams = {"providerUser","other"};
        ParamsUtil.checkNotNull(params,checkParams);

        JSONObject tmpProviderUser = JSONObject.fromObject(params.get("providerUser"));
        ProviderUser providerUser = (ProviderUser)PropertiesUtils.mapToObject(tmpProviderUser,ProviderUser.class);
        providerUser.setUpdateDate(new Date());
        //获取更新前的信息
        ProviderUser prevProvider = providerUserMapper.selectByPrimaryKey(providerUser.getDataId());
        //如果渠道资料已审核通过，则不再允许修改
//        if(prevProvider.getForDicQdshzt().equals("2")||prevProvider.getForDicQdshzt().equals("3")){
//            throw new RuntimeException("认证通过后，资料不允许修改");
//        }
        String prevQdlx = prevProvider.getForDicQdlx();
        String nowQdlx = providerUser.getForDicQdlx();
        String prevTbName = getDbName(prevQdlx);
        String providerUserId = providerUser.getDataId();
        if(prevQdlx.equals(nowQdlx)){
            //更新
            updateOtherInfoByCode(params,nowQdlx,providerUserId);
        }else{
            //删除之前类型表信息
            Map<String,Object> p = new HashMap<>(2);
            p.put("tbName",prevTbName);
            p.put("providerUserId",providerUserId);
            providerUserMapper.deleteOtherInfoBytbNameAndProviderId(p);
            // 新增类型信息到其他表
            insertOtherInfo(params,nowQdlx,providerUserId);
        }
        //如果之前渠道审核状态为  资料认证不通过，那么当渠道更新信息时，重新设置审核状态为未认证
        String emplId = intentUserAssignMapper.getEmplByProviderUserId(providerUserId);
        if(StringUtils.isEmpty(prevProvider.getForDicQdshzt())){
            providerUser.setForDicQdshzt("0");
            //已分配业务员，则通知业务员审核
            if(!StringUtils.isEmpty(emplId)){
                messageTemplateService.applyAuditInfo(emplId,providerUserId);
            }

        }else{
            if(prevProvider.getForDicQdshzt().equals("1")){
                providerUser.setForDicQdshzt("0");
                messageTemplateService.applyAuditInfo(providerUserId,emplId);
            }
        }

        providerUserMapper.updateByPrimaryKeySelective(providerUser);

        return true;
    }

    /**
     * 根据sysUserId获取意向渠道商信息
     * @param sysUserId
     * @return
     */
    public Map<String,Object> getIntentInfo(String sysUserId){

        //获取基本信息
        Map<String, Object> providerUser = providerUserMapper.selectBySysUserId(sysUserId);
        formate(providerUser);
        return providerUser;
    }

    /**
     * 根据provider_user的data_id获取意向渠道信息
     * @param provideruUserId
     * @return
     */
    public Map<String,Object> getIntentInfoByProviderId(String provideruUserId){
        //获取基本信息
        Map<String, Object> providerUser = providerUserMapper.getByProviderId(provideruUserId);
        formate(providerUser);
        return providerUser;
    }



    public boolean insertOtherInfo(Map<String,Object> params, String code,String providerUserId){
        JSONObject tmpObj = JSONObject.fromObject(params.get("other"));
        tmpObj.put("forProviderUser",providerUserId);
        tmpObj.put("dataId",StringUtils.uuid36());
        switch (code){
            //安装运维公司
            case AZYWGS :{
                ProviderUserSbgsAzywgs Azywgs = (ProviderUserSbgsAzywgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSbgsAzywgs.class);
                providerUserSbgsAzywgsMapper.insert(Azywgs);
                break;
            }
            //设备公司
            case SBGS :{
                ProviderUserSbgs sbgs = (ProviderUserSbgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSbgs.class);
                providerUserSbgsMapper.insert(sbgs);
                break;
            }
            //售电公司
            case SDGS :{
                ProviderUserSdgs Sdgs = (ProviderUserSdgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSdgs.class);
                providerUserSdgsMapper.insert(Sdgs);
                break;
            }
            //关系类渠道
            case GXLQD :{
                ProviderUserGxlqd Gxlqd = (ProviderUserGxlqd)PropertiesUtils.mapToObject(tmpObj,ProviderUserGxlqd.class);
                providerUserGxlqdMapper.insert(Gxlqd);
                break;
            }
            default:{}
        }
        return true;
    }

    /**
     * 根据渠道商类型码和渠道商id更新其他额外信息
     * @param params
     * @param providerUserId
     * @return
     */


    public boolean updateOtherInfoByCode(Map<String,Object> params, String code,String providerUserId){

        JSONObject tmpObj = JSONObject.fromObject(params.get("other"));
        tmpObj.put("forProviderUser",providerUserId);
        switch (code){
            //安装运维公司
            case AZYWGS :{
                ProviderUserSbgsAzywgs Azywgs = (ProviderUserSbgsAzywgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSbgsAzywgs.class);
                //更新
                providerUserSbgsAzywgsMapper.updateByPrimaryKeySelective(Azywgs);
                break;
            }
            //设备公司
            case SBGS :{
                ProviderUserSbgs sbgs = (ProviderUserSbgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSbgs.class);
                //更新
                providerUserSbgsMapper.updateByPrimaryKeySelective(sbgs);
                break;
            }
            //售电公司
            case SDGS :{
                ProviderUserSdgs Sdgs = (ProviderUserSdgs)PropertiesUtils.mapToObject(tmpObj,ProviderUserSdgs.class);
                //更新
                providerUserSdgsMapper.updateByPrimaryKeySelective(Sdgs);
                break;
            }
            //关系类渠道
            case GXLQD :{
                ProviderUserGxlqd Gxlqd = (ProviderUserGxlqd)PropertiesUtils.mapToObject(tmpObj,ProviderUserGxlqd.class);
                //更新
                providerUserGxlqdMapper.updateByPrimaryKeySelective(Gxlqd);
                break;
            }

            default:{}
        }
        return true;
    }

    /**
     * 获取所有未分配的意向渠道基本信息
     * @return
     */
    public DataPage selectUnAssign(Map<String, Object> params){
        //分页对象
        DataPage dataPage = new DataPage();

        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);

        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String, Object>> rows = intentUserMapper.selectUnAssign(params);
        dataPage.rows = formateData(rows);
        dataPage.total = intentUserMapper.countUnAssign(params);
        return dataPage;
    }

    public int countUnAssign(){
        return intentUserMapper.countUnAssign(null);
    }
    /**
     * 分配意向渠道给业务员
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean assign(Map<String, Object> params) throws RuntimeException{
        //检查参数完整性
        String[] checkParams = {"from","to","intentArr"};
        ParamsUtil.checkNotNull(params,checkParams);

        String from = params.get("from").toString();
        String to = params.get("to").toString();
        String tmpIntentArr = params.get("intentArr")+"";

        List<String> intentArr = Arrays.asList(tmpIntentArr.split(","));
        //删除之前的分配信息
        intentUserAssignMapper.deleteAssign(intentArr);
        //绑定信息（业务员，意向用户，分配者）到分配表
        intentUserAssignMapper.assignIntentToEmpl(intentArr,from,to,params.get("des")+"");
        //绑定业务员到provider_user表
        providerUserMapper.updateForEmpl(intentArr,to);
        //更新意向渠道状态值
        intentUserMapper.updateYxyhzt(intentArr,"1");
        //发送消息给业务员
        messageTemplateService.assignInfoToYw("1",to);
        //发送消息给渠道
//        for(int i=0;i<intentArr.size();i++){
//            messageTemplateService.assignInfoToIntent("1",intentArr.get(i),to);
//        }

        return true;
    }

    /**
     * 重新分配意向渠道
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean reAssign(Map<String, Object> params) throws RuntimeException{
        //检查参数完整性
        String[] checkParams = {"to","intentArr"};
        ParamsUtil.checkNotNull(params,checkParams);

        String to = params.get("to").toString();
        String tmpIntentArr = params.get("intentArr")+"";

        List<String> intentArr = Arrays.asList(tmpIntentArr.split(","));
        intentUserAssignMapper.reAssignIntent(intentArr,to,params.get("des")+"");
        messageTemplateService.assignInfoToYw("1",to);
        return true;
    }


    /**
     * 业务员获取自己跟进的意向渠道列表
     * @param params
     * @return
     */
    public DataPage intentForEmpl(Map<String, Object> params){
        //分页对象
        DataPage dataPage = new DataPage();

        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);

        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String, Object>> rows = intentUserAssignMapper.intentForEmpl(params);

        dataPage.rows = formateData(rows);
        dataPage.total = intentUserAssignMapper.countIntentForEmpl(params);
        return dataPage;
    }

    public DataPage intentForEmplContractSelect(Map<String, Object> params){
        //检查参数完整性
        String[] checkParams = {"emplId"};
        ParamsUtil.checkNotNull(params,checkParams);
        //分页对象
        DataPage dataPage = new DataPage();
        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);
        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String, Object>> rows = intentUserAssignMapper.intentForEmplContractSelect(params);

        dataPage.rows = formateData(rows);
        dataPage.total = intentUserAssignMapper.countIntentForEmplContractSelect(params);
        return dataPage;
    }

    /**
     * 获取意向渠道列表
     * @param params
     * @return
     */
    public DataPage getIntentFollowInfo(Map<String, Object> params){
        DataPage dataPage = new DataPage();
        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);

        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String, Object>> rows = intentUserAssignMapper.getIntentFollowInfo(params);

        dataPage.rows = formateData(rows);
        dataPage.total = intentUserAssignMapper.countIntentFollowInfo(params);

        return dataPage;
    }

    /**
     * 正式渠道列表
     * @param params
     * @return
     */
    public DataPage getRealProviderFollowInfo(Map<String, Object> params){
        DataPage dataPage = new DataPage();
        int pageIdx = StringUtils.parseInt(params.get("pageNumber") + "", 1);
        int pageSize = StringUtils.parseInt(params.get("pageSize") + "", 20);

        dataPage.pageindex = pageIdx;
        dataPage.pagesize = pageSize;
        params.put("from",(pageIdx-1)*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String, Object>> rows = intentUserAssignMapper.getRealProviderFollowInfo(params);

        dataPage.rows = formateData(rows);
        dataPage.total = intentUserAssignMapper.countRealProviderFollowInfo(params);

        return dataPage;
    }

    /**
     * 更新渠道审核状态
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int aduitIntent(Map<String, Object> params) throws RuntimeException{
        //检查参数完整性
        String[] checkParams = {"providerUserId","forDicQdshzt"};
        ParamsUtil.checkNotNull(params,checkParams);
        String providerUserId = params.get("providerUserId")+"";
        String emplId = intentUserAssignMapper.getEmplByProviderUserId(providerUserId);
        //认证审核不通过，需填写驳回原因
        if(params.get("forDicQdshzt").toString().equals("1")){
            String [] other = {"auditReason"};
            ParamsUtil.checkNotNull(params,other);
            messageTemplateService.auditIntentInfo(emplId,providerUserId,false);
        }else{
            //获取更新前的信息,检查信息完整性
            ProviderUser prevProvider = providerUserMapper.selectByPrimaryKey(providerUserId);
            String prevQdlx = prevProvider.getForDicQdlx();
            //获取
            Map<String,Object> authRequierdInfo = providerUserMapper.getAuthRequierdInfo(providerUserId);
            if(!checkCompletion(authRequierdInfo,prevQdlx)){
                throw new RuntimeException("渠道信息不全，不能通过认证");
            }
            messageTemplateService.auditIntentInfo(emplId,providerUserId,true);
        }
        return providerUserMapper.aduitIntent(params);
    }

    /**
     * 待跟进渠道
     * @return
     */
    public int readyToFollow(String emplId){
        return intentUserAssignMapper.getIntentNum(emplId,"0");
    }

    /**
     * 跟进中渠道
     * @return
     */
    public int hasFollowed(String emplId){
        return intentUserAssignMapper.getIntentNum(emplId,"1");
    }

    public boolean isPhoneOk(String phoneNo){
        ProviderUser providerUser = providerUserMapper.isPhoneNoOk(phoneNo);
        if(providerUser!=null){
            return false;
        }
        return true;
    }

    public List<Map<String, Object>> formateData(List<Map<String, Object>> rows){
        for(int i =0,len = rows.size(); i<len;i++){
            //将意向区域字段转成数组形式 "12313,7454"  =>  [12313,7454]
            formate(rows.get(i));
        }
        return rows;
    }

    public Map<String, Object> formate(Map<String, Object> obj){
        if(obj == null){
            return null;
        }
        String tmpCode = (String) obj.get("toRegionCode");
        //未完善渠道商意向合作区域时，返回空数组
        if(tmpCode == null || tmpCode.equals("")){
            String[] to_region_codes = {};

            obj.put("toRegionCode",to_region_codes);
            return obj;
        }
        String[] to_region_codes = tmpCode.split(",");

        obj.put("toRegionCode",to_region_codes);
        return obj;
    }

    public String getDbName(String qdlx){
        if(qdlx.equals("azywgs")){
            return "provider_user_sbgs_azywgs";
        }
        return "provider_user_"+qdlx;
    }

    //检查渠道必填信息完整性
    public boolean checkCompletion(Map<String, Object> des,String qdlx){

        String[] checkParams = {"businessLicenceUrl","name","address","visitingDemand","toRegionCode"};
        try{
            ParamsUtil.checkNotNull(des,checkParams);
        }catch (Exception E){
            return false;
        }
        switch (qdlx){
            //安装运维公司
            case AZYWGS :{
                if(!StringUtils.isNotEmpty(des.get("dlssLicenceUrl"))){
                    return false;
                }
                break;
            }
            //设备公司
            case SBGS :{
                if(!StringUtils.isNotEmpty(des.get("driverLicenceUrl"))){
                    return false;
                }
                break;
            }
            //售电公司
            case SDGS :{
                if(!StringUtils.isNotEmpty(des.get("energySaleLicenceUrl"))){
                    return false;
                }
                break;
            }
            //关系类渠道
            case GXLQD :{
                if(!StringUtils.isNotEmpty(des.get("relationDes"))){
                    return false;
                }
                break;
            }

            default:{}
        }

        return true;
    }
}
